unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Queue;

type
  TForm1 = class(TForm)
    Image1: TPaintBox;
    edtFirst: TEdit;
    Label1: TLabel;
    btnAction: TButton;
    procedure btnActionClick(Sender: TObject);
    procedure Image1Paint(Sender: TObject);
  end;

var
  Form1: TForm1;
  Matrix: array of Boolean;

implementation {$R *.dfm}

{ Actions }

procedure PaintMatrix(const data:Variant);
begin

end;

procedure PaintPrime(const data:Variant);
var
  i: Cardinal;
begin
  with Form1,Image1.Canvas do begin
    Lock;
    i := data - StrToInt(edtFirst.Text);
    Caption := IntToStr(i);
    Pixels[i mod Cardinal(Image1.Width), i div Cardinal(Image1.Width)] := clRed;
    Unlock;
  end;
end;

procedure SetPrime(const data:Variant);
begin
  Matrix[Integer(data)] := True;
  PaintPrime(data);
end;

procedure CalcPrime(const data:Variant);
  function IsPrime(number: Cardinal):Boolean;
  var
    i,last: Cardinal;
  begin
    Result := True;
    if number <= 3 then
      Exit
    else if (number mod 2) = 0 then
      Result := False
    else begin
      i := 3; last := Round(Sqrt(number));
      while (i <= last) and Result do begin
        Result := (number mod i) <> 0;
        Inc(i, 2);
      end;
    end;
  end;
begin
  if IsPrime(data) then
    Send(PaintPrime, data); // SendGUI(PaintPrime, data);
end;

procedure Controller(const data:Variant);
var
  i: Integer;
begin
  for i := data[0] to data[1] do begin
    Send(CalcPrime, i);
    if (i mod 1000) = 0 then Sleep(0);
  end;
end;

{ TForm1 }
procedure TForm1.btnActionClick(Sender: TObject);
var
  i,c: Integer;
begin
  i := StrToInt(edtFirst.Text);
  c := (Image1.Width * Image1.Height);
  Send(Controller, [i, i+c-1]);
end;

procedure TForm1.Image1Paint(Sender: TObject);
begin
  with Image1.Canvas do begin
    Brush.Color := clWhite;
    FillRect(ClipRect);
    Pen.Color := clBlack;
    Rectangle(ClipRect);
    // Draw(0,0, Bitmap);
  end;
end;

//procedure TForm1.Flush;
//var
//  i: Cardinal;
//begin
//  with form1,Image1.Canvas do begin
//    Lock;
//    i := data - StrToInt(edtFirst.Text);
//    Pixels[i mod Cardinal(Width), i div Cardinal(Width)] := clRed;
//    Unlock;
//  end;
//end;
//

end.
